package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.config.AiConfig;
import com.sky.context.BaseContext;
import com.sky.dto.AiChatDTO;
import com.sky.entity.AiChatRecord;
import com.sky.entity.Faq;
import com.sky.mapper.AiChatRecordMapper;
import com.sky.service.AiChatService;
import com.sky.service.FaqService;
import com.sky.service.NlpService;
import com.sky.vo.AiChatVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.*;

/**
 * AI聊天服务实现类
 */
@Service
@Slf4j
public class AiChatServiceImpl implements AiChatService {

    @Autowired
    private FaqService faqService;
    
    @Autowired
    private AiChatRecordMapper aiChatRecordMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private AiConfig aiConfig;
    
    @Autowired
    private NlpService nlpService;

    /**
     * 获取AI回答
     * @param aiChatDTO 聊天请求DTO
     * @return AI回答视图对象
     */
    @Override
    public AiChatVO getAiAnswer(AiChatDTO aiChatDTO) {
        String question = aiChatDTO.getQuestion();
        Long userId = BaseContext.getCurrentId();
        
        // 使用NLP进行意图识别
        String intent = nlpService.recognizeIntent(question);
        log.info("识别到用户意图: {}", intent);
        
        // 提取关键词
        List<String> keywords = nlpService.extractKeywords(question, 3);
        log.info("提取的关键词: {}", keywords);
        
        // 首先尝试从FAQ库中查找匹配的问题
        List<Faq> faqs = faqService.searchByKeyword(question);
        
        // 使用NLP计算相似度，找到最匹配的FAQ
        Faq bestMatch = null;
        double maxSimilarity = 0.0;
        
        for (Faq faq : faqs) {
            double similarity = nlpService.similarity(question, faq.getQuestion());
            if (similarity > maxSimilarity) {
                maxSimilarity = similarity;
                bestMatch = faq;
            }
        }
        
        // 如果找到相似度较高的FAQ，直接返回
        if (bestMatch != null && maxSimilarity > 0.7) {
            saveRecord(userId, question, bestMatch.getAnswer(), "faq");
            return AiChatVO.builder()
                    .answer(bestMatch.getAnswer())
                    .source("faq")
                    .build();
        }
        
        // FAQ中没有找到，调用AI接口
        String aiAnswer = callAiApi(question);
        
        // 保存聊天记录
        saveRecord(userId, question, aiAnswer, "ai");
        
        return AiChatVO.builder()
                .answer(aiAnswer)
                .source("ai")
                .build();
    }

    /**
     * 获取用户聊天历史记录
     * @param userId 用户ID
     * @return 聊天记录列表
     */
    @Override
    public List<AiChatRecord> getChatHistory(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }
        return aiChatRecordMapper.listByUserId(userId);
    }
    
    /**
     * 调用AI API获取回答
     * @param question 问题
     * @return AI回答
     */
    private String callAiApi(String question) {
        try {
            // 检查AI配置是否完整
            if (StringUtils.isBlank(aiConfig.getApiKey()) || 
                StringUtils.isBlank(aiConfig.getApiUrl()) || 
                StringUtils.isBlank(aiConfig.getModel())) {
                log.error("AI配置不完整，请检查application-dev.yml中的sky.ai配置");
                return "系统暂时无法使用AI服务，请联系管理员配置AI接口。";
            }
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiConfig.getApiKey());
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", aiConfig.getModel());
            
            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个专业的外卖助手，可以回答关于点餐、配送、菜品等问题。请保持回答简洁友好。");
            messages.add(systemMessage);
            
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", question);
            messages.add(userMessage);
            
            requestBody.put("messages", messages);
            requestBody.put("max_tokens", aiConfig.getMaxTokens());
            requestBody.put("temperature", aiConfig.getTemperature());
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            log.info("调用AI接口，请求参数: {}", JSON.toJSONString(requestBody));
            
            ResponseEntity<String> response = restTemplate.postForEntity(
                    aiConfig.getApiUrl(), 
                    entity, 
                    String.class);
            
            // 解析响应
            JSONObject jsonResponse = JSON.parseObject(response.getBody());
            JSONObject choices = jsonResponse.getJSONArray("choices").getJSONObject(0);
            JSONObject message = choices.getJSONObject("message");
            
            String answer = message.getString("content");
            log.info("AI回答: {}", answer);
            
            return answer;
        } catch (Exception e) {
            log.error("调用AI接口失败: {}", e.getMessage(), e);
            return "很抱歉，AI服务暂时不可用，请稍后再试。";
        }
    }
    
    /**
     * 保存聊天记录
     * @param userId 用户ID
     * @param question 问题
     * @param answer 回答
     * @param source 来源
     */
    private void saveRecord(Long userId, String question, String answer, String source) {
        try {
            AiChatRecord record = AiChatRecord.builder()
                    .userId(userId)
                    .question(question)
                    .answer(answer)
                    .createTime(LocalDateTime.now())
                    .build();
            
            aiChatRecordMapper.insert(record);
        } catch (Exception e) {
            log.error("保存聊天记录失败: {}", e.getMessage(), e);
        }
    }
} 